<script setup lang="ts">
// #ifdef MP-WEIXIN
import Pending from '@/basePackage/pages/deliveryOrder/components/Pending.vue'
import WaitPick from '@/basePackage/pages/deliveryOrder/components/WaitPick.vue'
import Pickup from '@/basePackage/pages/deliveryOrder/components/Pickup.vue'
import Delivered from '@/basePackage/pages/deliveryOrder/components/Delivered.vue'
// #endif
import { ref, reactive, type Component, defineAsyncComponent, computed, nextTick } from 'vue'
import IconBack from '@/components/icon-backto/index.vue'
import { type Address, type IcOrderPageParams, IcOrder, IcOrderStatus } from '@/apis/order/sameCityOrder/types'
import { useLocationStore } from '@/store/modules/location'
import { useScrollViewHeight } from '@/hooks'
import { onLoad } from '@dcloudio/uni-app'
import storage from '@/utils/storage'
import { storeToRefs } from 'pinia'

onLoad(({ back }) => {
    uni.$emit('updateTitle')
    // 判断是否是今天第一次进入页面
    if (storage.get('showFirstPopupTimeFlag') !== new Date().toLocaleDateString()) {
        firstPopup.value = true
    }
    // 记录今天的时间
    storage.set('showFirstPopupTimeFlag', new Date().toLocaleDateString())
    if (back === 'true') {
        firstPopup.value = false
        current.value = 3
    }
})
const { scrollViewHeight } = useScrollViewHeight(false)
const { getterLocation } = storeToRefs(useLocationStore())

const myLocation = computed(() => {
    return getterLocation.value?.coordinates || []
})

const firstPopup = ref(false)

//当前选中的tabs
const current = ref(0)

//tabs 列表
const list = reactive<
    {
        status: IcOrderPageParams['status']
        name: string
    }[]
>([
    {
        name: '待接单',
        status: IcOrderStatus.PENDING,
    },
    {
        name: '待取货',
        status: IcOrderStatus.TAKEN,
    },
    {
        name: '配送中',
        status: IcOrderStatus.PICKUP,
    },
    {
        name: '已送达',
        status: IcOrderStatus.DELIVERED,
    },
])

const ComponentMap: Record<number, Component> = reactive({
    0: defineAsyncComponent(() => import('./components/Pending.vue')),
    1: defineAsyncComponent(() => import('./components/WaitPick.vue')),
    2: defineAsyncComponent(() => import('./components/Pickup.vue')),
    3: defineAsyncComponent(() => import('./components/Delivered.vue')),
})
const orderListRef = ref()
const handleGetShopList = () => {
    console.log('触底了')
    // 通知子组件加载更多
    orderListRef.value.loadMore()
}

const navigation = (item: IcOrder) => {
    console.log(item)
    uni.openLocation({
        latitude: item.receiver.location.coordinates[1], // 目标位置的纬度
        longitude: item.receiver.location.coordinates[0], // 目标位置的经度
        name: item.receiver.address?.split('~')?.[1] || '', // 目标位置的名称
        address: item.receiver.address, // 目标位置的地址
        scale: 12.5, // 地图缩放级别，范围1-28
    })
}

const scrollTop = ref(0)
const oldScrollTop = ref(0)
const listScroll = (e: any) => {
    oldScrollTop.value = e.detail.scrollTop
}
const showToTop = computed(() => {
    return oldScrollTop.value > 200
})
// 滚动到页面顶部
const scrollToTop = async () => {
    scrollTop.value = oldScrollTop.value
    // 当调用此方法时，会先保存当前的滚动位置，并在下一个Vue的DOM更新周期开始时滚动到页面顶部
    await nextTick()
    // scrollTop.value 在300ms内慢慢变为0
    const duration = 300
    const startTime = performance.now()
    const animate = () => {
        const currentTime = performance.now()
        const elapsedTime = currentTime - startTime
        if (elapsedTime >= duration) {
            scrollTop.value = 0
            return
        }
        const progress = elapsedTime / duration
        scrollTop.value = 100 * (1 - progress)
        console.log(scrollTop.value)
        requestAnimationFrame(animate)
    }
    animate()
}
</script>

<template>
    <view class="content" :style="{ height: `${scrollViewHeight}` }">
        <view class="content__header">
            <IconBack style="margin-right: 30rpx" :url="'/pages/user/index'" :type="2"></IconBack>
            <view class="content__title">商家配送</view>
        </view>
        <view class="content__body">
            <view>
                <u-tabs
                    v-model="current"
                    :list="list"
                    height="100"
                    active-color="#333333"
                    inactive-color="#999999"
                    bar-width="50"
                    bar-height="12"
                    font-size="28"
                    bg-color="#F6F6F6"
                    itemWidth="180"
                    :bar-style="{ backgroundColor: '#4755E9' }"
                ></u-tabs>
            </view>

            <scroll-view class="content__body--shoplist" scroll-y :scroll-top="scrollTop" @scrolltolower="handleGetShopList" @scroll="listScroll">
                <!-- #ifndef MP-WEIXIN -->
                <component
                    :is="ComponentMap[current]"
                    ref="orderListRef"
                    :status="list[current].status"
                    :myLocation="myLocation"
                    @navigation="navigation"
                ></component>
                <!-- #endif -->
                <!-- #ifdef MP-WEIXIN -->
                <Pending
                    v-if="current === 0"
                    ref="orderListRef"
                    :status="list[current].status"
                    :myLocation="myLocation"
                    @navigation="navigation"
                ></Pending>
                <WaitPick
                    v-else-if="current === 1"
                    ref="orderListRef"
                    :status="list[current].status"
                    :myLocation="myLocation"
                    @navigation="navigation"
                ></WaitPick>
                <Pickup
                    v-else-if="current === 2"
                    ref="orderListRef"
                    :status="list[current].status"
                    :myLocation="myLocation"
                    @navigation="navigation"
                ></Pickup>
                <Delivered v-else ref="orderListRef" :status="list[current].status" :myLocation="myLocation" @navigation="navigation"></Delivered>
                <!-- #endif -->
            </scroll-view>
        </view>
        <view v-show="showToTop" class="back_to_up" @click="scrollToTop">
            <u-icon name="arrow-up" size="50"></u-icon>
        </view>
        <u-popup v-model="firstPopup" mode="center" border-radius="14" width="550" :mask-close-able="false">
            <view class="tips_container">
                <view class="tips_title">请确认</view>
                <view class="tips_content">请确保在指定时效内到达取货点和完成配送，取货和送货时注意使用礼貌用语。</view>
                <view class="tips_close">
                    <u-button plain type="primary" @click="firstPopup = false">我已知晓</u-button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<style lang="scss" scoped>
@include b(content) {
    display: flex;
    flex-direction: column;
    padding: 0 12rpx 0 16rpx;
    :deep(.uni-scroll-view:has(.done_list_container)) {
        background-color: white;
    }
    .back_to_up {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #eee;
        position: fixed;
        right: 35rpx;
        bottom: 100rpx;
        z-index: 999;
    }
    @include e(header) {
        height: 100rpx;
        display: flex;
        align-items: center;
        position: relative;
    }
    @include e(title) {
        font-size: 36rpx;
        font-weight: bold;
        color: #333333;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    @include e(body) {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        @include m(shoplist) {
            height: calc(100% - 108rpx);
        }
    }
}
.tips_container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 32px;
    padding-left: 44px;
    padding-right: 44px;
    padding-bottom: 32px;
    .tips_title {
        color: rgb(51, 51, 51);
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 34rpx;
    }
    .tips_content {
        color: rgb(51, 51, 51);
        font-size: 28rpx;
        font-weight: 400;
        line-height: 24px;
        margin-bottom: 60rpx;
    }
    .tips_close {
    }
}
</style>
